package com.motu.vertx.module.utility.webhandler;

import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import org.vertx.server.web.MainVerticle;

public class RefundHandler extends BaseWebHandler{
	private final static Logger logger = LoggerFactory.getLogger(RefundHandler.class);
	private static final String tableName = "refundconfig";//退款配置包

	private static Pool jdbcClientServer = null;
	private static Pool jdbcClientRefund = null; //
	//新框架是game库的iaprecord表 旧框架是server库的iaprecord_all表
	private static String tableNameRefund = ""; //查询退款记录


	public static void init(Pool jdbcClient, Pool jdbcClientTmp, String tableNameTmp){
		jdbcClientServer = jdbcClient;
		jdbcClientRefund = jdbcClientTmp;
		tableNameRefund = tableNameTmp;
	}

	public static void list(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		getTableList(routingContext,jdbcClientServer, tableName);
	}
	public static void add(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		addToTable(routingContext, jdbcClientServer, tableName, null);
	}

	public static void delete(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		deleteFromTable(routingContext,jdbcClientServer, tableName);
	}
	
	public static void update(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		updateToTable(routingContext, jdbcClientServer, tableName, null);
	}

	public static void getone(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		getFromTable(routingContext,jdbcClientServer, tableName);

	}

	/**
	 * 玩家退款统计
	 * @param routingContext
	 * @param json
	 * @param adminName
	 * @param client
	 */
	public static void voided_search(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		boolean isNewGameFrame = tableNameRefund == "iaprecord";
	    String usertable = "";
	    //新架构查询userindo  老架构 查询userloginlog2表
		if(isNewGameFrame){
			usertable =  " userinfo ";
		} else {
			usertable =  " (SELECT userid as id ,MAX(offlinetime)  as logintime FROM userloginlog2 GROUP BY userid) ";
		}
		String sql = "SELECT a.userid,a.username,b.logintime,a.voidedtime,count(1) as num,sum(money) as money FROM " + tableNameRefund + " a , " + usertable + " b where a.userid=b.id and ";
		if (json.getInteger("type") == 0) {
			sql +=  "voided in (1,2)"; //全部(苹果 谷歌)退款
		}else {
			sql += "voided = "+ json.getInteger("type");
		}
		JsonArray params = new JsonArray();
		if (json.containsKey("userid")) {
			sql += " and a.userid = ? ";
			params.add(json.getLong("userid"));
		}
		if (json.containsKey("stime")) {
			sql += " and a.time >= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			sql += " and a.time <= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		if (json.containsKey("voidedstime")) {
			sql += " and a.voidedtime >= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("voidedstime")));
		}
		if (json.containsKey("voidedetime")) {
			sql += " and a.voidedtime <= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("voidedetime")));
		}
		sql += " group by a.userid " + json.getString("orderby") + " desc;";
		MysqlTool.queryJsonArrayFromDb(jdbcClientRefund, sql, params, handler->{
			if(handler.succeeded()) {
				JsonArray list = handler.result();
				int max = list.size();
				if (max < 1) {
					sendHttpResponse(routingContext.response(), new JsonObject());
					return;
				}
				String sql_banned = "";
				//新框架是game库的userextinfo表 旧框架是server库的alluser表
				if(isNewGameFrame){
					sql_banned =  "select userid,reason from banneduser where bantime>UNIX_TIMESTAMP(now()) and userid in (";
				} else {
					sql_banned =  "select userid,status from alluser where userid in (";
				}
				String sql_total = "select count(id) as totalnum,sum(money) as totalmoney,userid from " + tableNameRefund + " where userid in (";//该玩家总的充值记录
				for(int i=0; i<max; i++) {
					list.getJsonObject(i).put("isbanned", 0);
					sql_banned += list.getJsonObject(i).getLong("userid");
					sql_total += list.getJsonObject(i).getLong("userid");
					if (i < (max - 1)) {
						sql_banned += ",";
						sql_total += ",";
					}
				}
				sql_banned += ");";
//				if (isNewGameFrame) {
//					sql_total += ");";
//				}else {
					sql_total += ") group by userid;";
//				}

				Future<JsonArray> fut_banned = MysqlTool.queryJsonArrayFromDb(jdbcClientServer, sql_banned, new JsonArray());
				Future<JsonArray> fut_total = MysqlTool.queryJsonArrayFromDb(jdbcClientRefund, sql_total, new JsonArray());
				Future.all(fut_banned, fut_total).onComplete(ar->{

					if(ar.succeeded()){
						JsonArray result = new JsonArray();
						JsonArray list_banned = fut_banned.result();
						JsonArray list_total = fut_total.result();
						int max_banned = list_banned.size();
						int max_total = list_total.size();
						for(int i=0; i<max; i++) {
							long userid1 = list.getJsonObject(i).getLong("userid");
							if (isNewGameFrame){
								for(int k=0; k<max_banned; k++) {  //添加是否封号标志
									long userid2 = list_banned.getJsonObject(k).getLong("userid");
									if(userid1 == userid2) {
										list.getJsonObject(i).put("isbanned", 1).put("reason", list_banned.getJsonObject(k).getString("reason"));
									}
								}
							}else {
								for(int k=0; k<max_banned; k++) {  //添加是否封号标志
									long userid2 = list_banned.getJsonObject(k).getLong("userid");
									if(isNewGameFrame){
										if(userid1 == userid2) {
											list.getJsonObject(i).put("isbanned", 1).put("reason", list_banned.getJsonObject(k).getString("reason"));
										}
									} else {
										if(userid1 == userid2 && list_banned.getJsonObject(k).getInteger("status") == 99) {
											list.getJsonObject(i).put("isbanned", 1).put("reason", list_banned.getJsonObject(k).getString("reason"));
										}
									}

								}
							}

							//添加总的充值信息
							for(int j=0; j<max_total; j++) {
								if(userid1 == list_total.getJsonObject(j).getLong("userid").longValue()) {
									list.getJsonObject(i).put("totalnum", list_total.getJsonObject(j).getInteger("totalnum")).put("totalmoney", list_total.getJsonObject(j).getDouble("totalmoney"));
								}
							}

							if (json.getInteger("isbanned") == 1) {  //只显示未封号
								if (list.getJsonObject(i).getInteger("isbanned") == 0) {
									result.add(list.getJsonObject(i));
								}
							} else {
								result = list;
							}
						}
						sendHttpResponse(routingContext.response(), new JsonObject().put("rets", result));

					}else{
						sendHttpResponseError(routingContext.response(), ar.cause().getMessage());
					}
				});
			} else {
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(routingContext.response(), handler.cause().getMessage());
			}
		});
	}

	/**
	 * 根据玩家id获取退款记录
	 * @param routingContext
	 * @param json
	 * @param adminName
	 * @param client
	 */
	public static void search_userid_voided(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		String sql = "SELECT * FROM " + tableNameRefund + " WHERE userid=? and voided !=0 ";
		JsonArray params = new JsonArray();
		params.add(json.getLong("userid"));
		if (json.containsKey("voidedstime")) {
			sql += " and voidedtime >= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("voidedstime")));
		}
		if (json.containsKey("voidedetime")) {
			sql += " and voidedtime <= ? ";
			params.add(TimeUtils.getTimeStrIntValue(json.getString("voidedetime")));
		}
		MysqlTool.queryJsonArrayFromDb(jdbcClientRefund, sql, params, handle->{
			if (handle.succeeded()) {
				JsonArray list = handle.result();
				sendHttpResponse(routingContext.response(), new JsonObject().put("rets", list));
			} else {
				sendHttpResponseError(routingContext.response(), handle.cause().getMessage());
			}
		});
	}
}
